package lock;

import cn.hutool.core.date.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;

/**
 * @description: 测试clhLock
 * @author: kanggw
 * @date: 2023/6/14
 **/
public class LockTest {


    public void testCLHLock() throws InterruptedException {

        final  int turns = 100000;
        final int threads = 10;

        ExecutorService pool = Executors.newFixedThreadPool(threads);

        CLHLock lock = new CLHLock();

        CountDownLatch countDownLatch = new CountDownLatch(threads);

        StopWatch watch = StopWatch.create("开始");
        watch.start();
        for (int i = 0; i < threads; i++) {
            pool.submit(() -> {
                for (int j = 0; j < turns; j++) {
                    IncrementData.lockAndIncrease(lock);
                }
                System.out.println(Thread.currentThread().getName() + "处理完毕");
                countDownLatch.countDown();
            });
        }

        countDownLatch.await();
        System.out.println("时长" + watch.prettyPrint());
        System.out.println("累加结果：" + IncrementData.sum);
        pool.shutdown();
        System.out.println("end");
    }

    public static void main(String[] args) throws InterruptedException {
        LockTest lockTest = new LockTest();

        lockTest.testCLHLock();
    }


    public static class IncrementData{
        public static int sum = 0;

        public static void lockAndIncrease(Lock lock) {

            lock.lock();

            try {
                sum++;
            } finally {
                lock.unlock();
            }
        }

    }

}


